import collections


class Solution:
    def subarraysWithKDistinct(self, A: list, K: int) -> int:
        def asMostK(array, k):
            res = 0
            left = 0
            right = 0
            counter = collections.Counter()
            while right < len(array):
                if counter[array[right]] == 0:
                    k -= 1
                counter[array[right]] += 1
                while k < 0:
                    counter[array[left]] -= 1
                    if counter[array[left]] == 0:
                        k += 1
                    left += 1
                res += (right - left + 1)
                right += 1
            return res

        return asMostK(A, K) - asMostK(A, K - 1)
